<template>
  <div>
    <!-- 数据统计 -->
    <el-card shadow="never" class="mb-16px">
      <template #header>
        <div class="flex items-center">
          <Icon icon="ep:data-analysis" class="mr-8px" />
          <span class="text-16px font-bold">数据统计</span>
        </div>
      </template>
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <div class="text-center p-16px">
              <div class="text-12px text-gray-400 mb-8px">总库存</div>
              <CountTo
                class="text-32px font-bold text-blue-500"
                :start-val="0"
                :end-val="statistics.totalStock"
                :duration="2000"
              />
            </div>
          </el-col>
          <el-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <div class="text-center p-16px">
              <div class="text-12px text-gray-400 mb-8px">总销量</div>
              <CountTo  
                class="text-32px font-bold text-green-500"
                :start-val="0"
                :end-val="statistics.totalSales"
                :duration="2000"
              />
            </div>
          </el-col>
          <el-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <div class="text-center p-16px">
              <div class="text-12px text-gray-400 mb-8px">总回收数量</div>
              <CountTo
                class="text-32px font-bold text-orange-500"
                :start-val="0"
                :end-val="statistics.totalRecycled"
                :duration="2000"
              />
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>

    <el-row :gutter="16">
      <!-- 区域销售分析 -->
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-16px">
        <el-card shadow="never">
          <template #header>
            <div class="flex items-center">
              <Icon icon="ep:location" class="mr-8px" />
              <span class="text-16px font-bold">区域销售分析</span>
            </div>
          </template>
          <el-skeleton :loading="loading" animated>
            <Echart :options="pieOptions" :height="320" />
          </el-skeleton>
        </el-card>
      </el-col>

      <!-- 销售统计 -->
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-16px">
        <el-card shadow="never">
          <template #header>
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <Icon icon="ep:histogram" class="mr-8px" />
                <span class="text-16px font-bold">销售统计</span>
              </div>
              <el-select v-model="selectedYear" size="small" @change="fetchMonthlySales">
                <el-option
                  v-for="year in yearOptions"
                  :key="year"
                  :label="year + '年'"
                  :value="year"
                />
              </el-select>
            </div>
          </template>
          <el-skeleton :loading="loading" animated>
            <Echart :options="barOptions" :height="320" />
          </el-skeleton>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { EChartsOption } from 'echarts'
import { CardApi } from '@/api/dc/card'

defineOptions({ name: 'DeliveryCardDashboard' })

// 响应式数据
const loading = ref(true)
const statistics = ref({
  totalStock: 0,
  totalSales: 0,
  totalRecycled: 0
})

// 年份选择
const currentYear = new Date().getFullYear()
const selectedYear = ref(currentYear)
const yearOptions = computed(() => {
  const years: number[] = []
  for (let i = currentYear - 2; i <= currentYear; i++) {
    years.push(i)
  }
  return years
})

// 饼图配置
const pieOptions = ref<EChartsOption>({
  title: {
    text: '区域销售分布',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 14
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: 'middle'
  },
  series: [
    {
      name: '销售区域',
      type: 'pie',
      radius: '50%',
      center: ['60%', '50%'],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})

// 柱状图配置
const barOptions = ref<EChartsOption>({
  title: {
    text: '月度销售统计',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 14
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: ['实体卡', '配送卡'],
    top: '10%'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '20%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '实体卡',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#409EFF'
      }
    },
    {
      name: '配送卡',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#67C23A'
      }
    }
  ]
})

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const data = await CardApi.getStatistics()
    statistics.value = data || {
      totalStock: 23698,
      totalSales: 23698,
      totalRecycled: 23698
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 使用模拟数据
    statistics.value = {
      totalStock: 23698,
      totalSales: 23698,
      totalRecycled: 23698
    }
  }
}

// 获取区域销售分析数据
const fetchRegionSales = async () => {
  try {
    const data = await CardApi.getRegionSalesAnalysis()
    const regionData = data || [
      { name: '华北', value: 2840 },
      { name: '华东', value: 3200 },
      { name: '华南', value: 2100 },
      { name: '华中', value: 1800 },
      { name: '西南', value: 1500 },
      { name: '西北', value: 1200 },
      { name: '东北', value: 800 }
    ]
    
    // 更新饼图数据
    if (pieOptions.value.legend && typeof pieOptions.value.legend === 'object' && !Array.isArray(pieOptions.value.legend)) {
      pieOptions.value.legend.data = regionData.map(item => item.name)
    }
    if (pieOptions.value.series && pieOptions.value.series[0]) {
      pieOptions.value.series[0].data = regionData
    }
  } catch (error) {
    console.error('获取区域销售数据失败:', error)
    // 使用模拟数据
    const regionData = [
      { name: '华北', value: 2840 },
      { name: '华东', value: 3200 },
      { name: '华南', value: 2100 },
      { name: '华中', value: 1800 },
      { name: '西南', value: 1500 },
      { name: '西北', value: 1200 },
      { name: '东北', value: 800 }
    ]
    if (pieOptions.value.legend && typeof pieOptions.value.legend === 'object' && !Array.isArray(pieOptions.value.legend)) {
      pieOptions.value.legend.data = regionData.map(item => item.name)
    }
    if (pieOptions.value.series && pieOptions.value.series[0]) {
      pieOptions.value.series[0].data = regionData
    }
  }
}

// 获取月度销售统计数据
const fetchMonthlySales = async () => {
  try {
    const data = await CardApi.getMonthlySalesStatistics(selectedYear.value)
    const salesData = data || {
      physicalCard: [320, 332, 301, 334, 390, 330, 320, 380, 290, 350, 360, 400],
      deliveryCard: [220, 182, 191, 234, 290, 330, 310, 280, 250, 300, 320, 350]
    }
    
    // 更新柱状图数据
    if (barOptions.value.series && barOptions.value.series[0]) {
      barOptions.value.series[0].data = salesData.physicalCard
    }
    if (barOptions.value.series && barOptions.value.series[1]) {
      barOptions.value.series[1].data = salesData.deliveryCard
    }
  } catch (error) {
    console.error('获取月度销售数据失败:', error)
    // 使用模拟数据
    if (barOptions.value.series && barOptions.value.series[0]) {
      barOptions.value.series[0].data = [320, 332, 301, 334, 390, 330, 320, 380, 290, 350, 360, 400]
    }
    if (barOptions.value.series && barOptions.value.series[1]) {
      barOptions.value.series[1].data = [220, 182, 191, 234, 290, 330, 310, 280, 250, 300, 320, 350]
    }
  }
}

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchStatistics(),
      fetchRegionSales(),
      fetchMonthlySales()
    ])
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  initData()
})
</script>

<style scoped>
.text-center {
  text-align: center;
}
</style>
